package meterMonitor.controller;

import meterMonitor.biz.AreaBiz;
import meterMonitor.biz.MeterBiz;
import meterMonitor.consts.ResponseCode;
import meterMonitor.framework.auth.AuthorityType;
import meterMonitor.framework.auth.FireAuthority;
import meterMonitor.model.Area;
import meterMonitor.model.Meter;
import meterMonitor.util.BizException;
import meterMonitor.util.StringUtils;
import meterMonitor.util.excel.domain.ExcelColumn;
import meterMonitor.vo.BaseResponseData;
import meterMonitor.vo.SetIntervalTimeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by admin on 2019/1/3.
 */
@RequestMapping("meterManager")
@RestController
public class MeterManagerController extends BaseController {

    @Autowired
    private MeterBiz meterBiz;
    @Autowired
    private AreaBiz areaBiz;


    /**
     * 水表管理页面
     *
     * @param mv
     * @return
     */
    @RequestMapping("meterManagerIndex.do")
    @FireAuthority(authorityTypes = AuthorityType.Edit)
    public ModelAndView index(ModelAndView mv) {
        return mv;
    }

    /**
     * 查询所有水表
     *
     * @return
     */
    @RequestMapping("queryMeter.do")
    @ResponseBody
    @FireAuthority(authorityTypes = AuthorityType.Edit)
    public List<Meter> queryMeter() {
        return meterBiz.queryMeter(null);
    }

    /**
     * yy:根据设备类型查询所有设备
     *
     * @return
     */
    @RequestMapping("queryMeterByDevice.do")
    @ResponseBody
    @FireAuthority(authorityTypes = AuthorityType.Edit)
    public List<Meter> queryMeter(String deviceTypeCode) {

        int type=Integer.parseInt(deviceTypeCode);
        System.out.println(type+999);

        return meterBiz.queryMeterByDevice(type);
    }

    /**
     * 不带条件查询查询全部Meter
     *
     * @return
     */
    @RequestMapping("queryAllMeter.do")
    @ResponseBody
    @FireAuthority(authorityTypes = AuthorityType.Edit)
    public List<Meter> queryAllMeter() {
        return meterBiz.queryAllMeter();
    }


    /**
     * 根据类型查出对应的表
     */
    @RequestMapping("queryMeterByType.do")
    @ResponseBody
    @FireAuthority(authorityTypes = AuthorityType.Edit)
    public List<Meter> queryMeterByType(int type) {
        return meterBiz.queryMeter(null);
    }



    /**
     * 新增
     *
     * @param meter
     * @return
     */
    @RequestMapping("add.do")
    @ResponseBody
    @FireAuthority(authorityTypes = AuthorityType.Edit)
    public BaseResponseData saveMeter(Meter meter) {
        BaseResponseData response = new BaseResponseData();
        try {
            meterBiz.insert(meter);
            response.setCode(ResponseCode.SUCCESS);
        } catch (Exception ex) {
            logger.error("新增水表信息异常", ex);
            response.setCode(ResponseCode.DEFAULT_EXCEPTION);
            response.setMessage(null != ex.getMessage() ? ex.getMessage() : "系统异常！请联系管理员");

        }
        return response;
    }


    /**
     * 修改
     *
     * @param meter
     * @return
     */
    @RequestMapping("update.do")
    @ResponseBody
    @FireAuthority(authorityTypes = AuthorityType.Edit)
    public BaseResponseData update(Meter meter) {
        BaseResponseData baseResponseData = new BaseResponseData();
        try {
            meterBiz.update(meter);
            baseResponseData.setCode(ResponseCode.SUCCESS);
        } catch (Exception ex) {
            this.logger.error(ex.getMessage(), ex);
            baseResponseData.setCode(ResponseCode.DATA_EXCEPTION);
            baseResponseData.setMessage(null != ex.getMessage() ? ex.getMessage() : "系统异常！请联系管理员");
        }
        return baseResponseData;
    }


    /**
     * 删除
     *
     * @param meter
     * @return
     */
    @ResponseBody
    @RequestMapping("delete.do")
    @FireAuthority(authorityTypes = AuthorityType.Edit)
    public BaseResponseData delete(Meter meter) {
        BaseResponseData baseResponseData = new BaseResponseData();
        try {
            meterBiz.deleteMeterById(meter.getMeterCode());
            baseResponseData.setCode(ResponseCode.SUCCESS);
        } catch (Exception e) {
            baseResponseData.setCode(ResponseCode.DATA_EXCEPTION);
            baseResponseData.setMessage("系统异常！请联系管理员");
        }
        return baseResponseData;
    }


    /**
     * @param request  可以携带参数查询（本方法不带条件查询，所以可以不需要request）
     * @param response 查询完响应（必须要）
     *                 <p>
     *                 导出查询的Excel
     */
    @RequestMapping("exportExcel.do")
    @ResponseBody
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        // //double保留2位小数四舍五入
        // DecimalFormat df = new DecimalFormat("#0.00");
        // Calendar cal = Calendar.getInstance();
        // //获得一个月的天数
        // int days = cal.getActualMaximum(java.util.Calendar.DAY_OF_MONTH);
        //
        // List<MeterStr> liststr = null;
        // try {
        //     List<Meter> list = meterBiz.queryAllMeter();
        //     liststr = new ArrayList<MeterStr>();
        //     DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //     String manufactureDate = null;
        //     String addTime = null;
        //     for (Meter meter : list) {
        //         MeterStr meterStr = new MeterStr();
        //         if (meter.getAddedTime() != null) {
        //             addTime = dateFormat.format(meter.getAddedTime());
        //             meterStr.setAddedTime(addTime);
        //         } else {
        //             meterStr.setAddedTime(null);
        //         }
        //         meterStr.setDeviceName(meter.getDeviceName());
        //         meterStr.setAnotherName(meter.getAnotherName());
        //         meterStr.setDescrition(meter.getDescrition());
        //         meterStr.setDeviceTypeCode(meter.getDeviceTypeCode());
        //         meterStr.setPkid(meter.getMeterCode());
        //         meterStr.setLastModifyTime(meter.getLastModifyTime());
        //         meterStr.setStandardNight(meter.getStandardNight());
        //         meterStr.setStandardDay(meter.getStandardDay());
        //         if (meter.getStandardNight() != null || meter.getStandardDay() != null) {
        //             meterStr.setDaytotal(meter.getStandardDay() + meter.getStandardNight());
        //         }
        //         //设置月的标准量
        //         meterStr.setMonthtotal(meterStr.getDaytotal() * days);
        //         //设置天最大流量
        //         meterStr.setMaxflow(df.format(meterStr.getDaytotal() / 24));
        //         liststr.add(meterStr);
        //     }
        // } catch (Exception ex) {
        //     this.logger.error(ex.getMessage(), ex);
        // }
        //
        // //导出功能
        // List<MeterStr> feeForDetailDtos = liststr;
        // ExcelHead head = new ExcelHead();
        // head.setColumns(setColumns());
        // //生成Excel文件流
        // ExcelUtil.getInstanse().exportExcel(head, "导出模板", feeForDetailDtos, response);
    }

    //构建Excel列表
    private List<ExcelColumn> setColumns() {

        List<ExcelColumn> columns = new ArrayList<>();
        String[] fields = {"addedTime", "anotherName", "deviceName", "daytotal", "monthtotal"};
        String[] headers = {"安装日期", "水表位置", "芯片编号", "当日总量", "当月总量"};
        for (int i = 0; i < fields.length; i++) {
            columns.add(new ExcelColumn(i, fields[i], headers[i]));
        }
        return columns;
    }

    //设置频率
    @RequestMapping("setIntervalTime.do")
    @ResponseBody
    @FireAuthority(authorityTypes = AuthorityType.Edit)
    public BaseResponseData setIntervalTime(SetIntervalTimeVo vo) {
        BaseResponseData baseResponseData = new BaseResponseData();
        try {
            if (vo == null || StringUtils.isBlank(vo.getPkids())) {
                throw new BizException("输入参数不正确，请检查！");
            }
            meterBiz.setIntervalTime(vo);
            //meterBiz.getConfigAndUpdate();
            baseResponseData.setCode(ResponseCode.SUCCESS);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            baseResponseData.setCode(ResponseCode.DATA_EXCEPTION);
            baseResponseData.setMessage(e.getMessage());
        }
        return baseResponseData;
    }

    //从厂商api获取频率并更新到设备表
    @RequestMapping("getIntervalTimeAndUpdate.do")
    @ResponseBody
    @FireAuthority(authorityTypes = AuthorityType.SystemAuth)
    public BaseResponseData getIntervalTimeAndUpdate() {
        BaseResponseData baseResponseData = new BaseResponseData();
        try {
            meterBiz.getConfigAndUpdate();
            baseResponseData.setCode(ResponseCode.SUCCESS);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            baseResponseData.setCode(ResponseCode.DATA_EXCEPTION);
            baseResponseData.setMessage(e.getMessage());
        }
        return baseResponseData;
    }

    /**
     * 更换设备
     *
     * @param meter
     * @return
     */
    @RequestMapping("fixMeter.do")
    @ResponseBody
    @FireAuthority(authorityTypes = AuthorityType.Edit)
    public BaseResponseData fixMeter(Meter meter) {
        BaseResponseData baseResponseData = new BaseResponseData();
        try {
            meterBiz.fixMeter(meter);
            baseResponseData.setMessage("更改成功！");
            baseResponseData.setCode(ResponseCode.SUCCESS);
            return baseResponseData;
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            baseResponseData.setMessage("更改设备失败！");
            baseResponseData.setCode(ResponseCode.DATA_EXCEPTION);
        }
        return baseResponseData;
    }

    //更换水表
    @ResponseBody
    @RequestMapping("changeMeter.do")
    @FireAuthority(authorityTypes = AuthorityType.Edit)
    public BaseResponseData changeMter(String deviceName, String dateTime) {
        BaseResponseData responseData = new BaseResponseData();
        try {
            //meterBiz.insertHistory(deviceName,dateTime);

            // detailBiz.insertSelective(deviceName);

            responseData.setMessage("保存成功!");
            responseData.setCode(ResponseCode.SUCCESS);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            responseData.setMessage("保存失败!");
            responseData.setCode(ResponseCode.SYSTEM_EXCEPTION);
        }

        return responseData;

    }

    /**
     * 查询设备名称
     *
     * @return
     */
    @RequestMapping("findDeviceName.do")
    @ResponseBody
    @FireAuthority(authorityTypes = AuthorityType.Edit)
    public List<String> findDeviceName() {
        List<String> list = new ArrayList<>();
        try {
            list = meterBiz.queryDeviceName();
            return list;
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }
        return list;
    }

    /**
     * 查询所有区域
     */
    @RequestMapping("findArea.do")
    @ResponseBody
    @FireAuthority(authorityTypes = AuthorityType.Edit)
    public List<String> getAreaNames() {
        List<String> listStr = new ArrayList<>();
        try {
            List<Area> list = areaBiz.getfandAllArea(0);
            for (Area area : list) {
                listStr.add(area.getAreaName());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return listStr;
    }

    /**
     * 查询所有区域
     */
    @RequestMapping("allAreas.do")
    @ResponseBody
    @FireAuthority(authorityTypes = AuthorityType.Edit)
    public List<Area> getAreas() {
        List<Area> list = new LinkedList<>();
        try {
            list = areaBiz.getfandAllArea(0);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return list;
    }
}
